<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

  <style> 

    .box {
      width: 100px;
      height: 100px;
      background-color: blue;
    }
  </style>
</head>
<body>

  <div class="box"></div>

  <script>

    function debounce(fn, delay, options) {
      let timer = null;
      let maxWaitTimer = null;
      let lastArgs = null;
      let lastThis = null;

      const {
        leading = false,
        trailing = true,
        maxWait,
      } = options;

      return function (...args) {
        lastArgs = args;
        lastThis = this

        clearTimeout(timer)

        if (leading && !timer) {
          fn.apply(lastThis, lastArgs)
          clearTimeout(maxWaitTimer)
          maxWaitTimer = null
        }

        timer = setTimeout(() => {
          if (trailing) {
            fn.apply(lastThis, lastArgs)
          }
          clearTimeout(maxWaitTimer)
          maxWaitTimer = null
          timer = null
        }, delay)

        if (maxWait && !maxWaitTimer) {
          maxWaitTimer = setTimeout(() => {
            fn.apply(lastThis, lastArgs)
            clearTimeout(timer)
            maxWaitTimer = null
          }, maxWait)
        }

      }
    }

    const debounceClick = debounce(() => {
      console.log('333')
    }, 1000, {
      leading: true,
      trailing: true,
      maxWait: 3000
    })

    document.querySelector('.box').onclick = () => {
      debounceClick()
    }

    
  </script>
</body>
</html>